<template>
  <div class="stat-card">
    <div class="card-content">
      <div class="card-title">
        <div class="icon-wrapper" :style="{ backgroundColor: iconBgColor }">
          <span v-html="icon" class="icon"></span>
        </div>
        <span>{{ title }}</span>
      </div>
      <div class="card-value">{{ value }}</div>
      <div class="card-comparison" :style="{ color: comparison.isUp ? '#28a745' : '#dc3545' }">
        较上月{{ comparison.isUp ? '增加' : '减少' }} {{ comparison.text }}
      </div>
    </div>
    <div class="chart-middle-container">
      <div ref="middleChart" class="middle-chart"></div>
    </div>
    <div class="chart-container">
      <div ref="chart" class="chart"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, defineEmits } from 'vue';
import * as echarts from 'echarts';
import api from '@/utils/axios.js';

const emit = defineEmits(['updateStatsData']);

const props = defineProps<{
  icon: string;
  iconBgColor: string;
  title: string;
  value: string;
  comparison: {
    isUp: boolean;
    text: string;
  };
}>();

const API_BASE_URL = 'http://localhost:8080/api/auth';
const chart = ref<HTMLElement | null>(null);
const middleChart = ref<HTMLElement | null>(null);

// 获取月度警员数量
const getOfficerCountByMonth = async () => {
  try {
    const response = await api.get(`${API_BASE_URL}/officers`);
    const officers = response.data?.data || [];
    console.log('获取到的警员数据:', officers);

    // 简单模拟月度数据，实际应该根据入职日期等统计
    const monthlyData = [
      officers.length * 0.8,
      officers.length * 0.85,
      officers.length * 0.9,
      officers.length * 0.95,
      officers.length,
      officers.length * 1.05
    ];
    console.log('月度警员数量数据:', monthlyData);
    return monthlyData;
  } catch (error) {
    console.error('获取警员数量失败:', error);
    return [];
  }
};

// 获取不同部门的警员数量
const getOfficerCountByDepartment = async () => {
  try {
    const response = await api.get(`${API_BASE_URL}/officers`);
    const officers = response.data?.data || [];
    console.log('获取到的警员数据:', officers);

    // 按部门分组统计警员数量
    const departmentMap = new Map();
    officers.forEach(officer => {
      if (officer.department) {
        if (departmentMap.has(officer.department)) {
          departmentMap.set(officer.department, departmentMap.get(officer.department) + 1);
        } else {
          departmentMap.set(officer.department, 1);
        }
      }
    });

    // 转换为数组
    const departmentData = Array.from(departmentMap.values());
    const departmentNames = Array.from(departmentMap.keys());
    console.log('部门名称:', departmentNames);
    console.log('部门警员数量数据:', departmentData);

    return { departmentData, departmentNames };
  } catch (error) {
    console.error('获取部门警员数量失败:', error);
    return { departmentData: [], departmentNames: [] };
  }
};

// 获取不同时段的平均巡逻时长
const getAveragePatrolTimeByShift = async () => {
  try {
    // 修正API路径
    const response = await api.get(`${API_BASE_URL}/shifts`);
    const shifts = response.data || [];
    console.log('获取到的排班数据:', response.data);

    // 按早班、中班、晚班、夜班分组
    const shiftGroups = {
      '早班': [],
      '中班': [],
      '晚班': [],
      '夜班': []
    };

    shifts.forEach(shift => {
      // 假设可以从startTime和endTime计算时长
      // 正确解析日期时间
      const startDateTime = new Date(`${shift.date}T${shift.startTime}`);
      const endDateTime = new Date(`${shift.date}T${shift.endTime}`);
      const duration = (endDateTime.getTime() - startDateTime.getTime()) / (1000 * 60 * 60); // 小时

      // 根据时间判断班次
      const hour = startDateTime.getHours();
      let shiftType = '早班';
      if (hour >= 8 && hour < 12) shiftType = '早班';
      else if (hour >= 12 && hour < 18) shiftType = '中班';
      else if (hour >= 18 && hour < 22) shiftType = '晚班';
      else shiftType = '夜班';

      shiftGroups[shiftType].push(duration);
    });

    // 计算每组的平均时长
    const shiftData = Object.values(shiftGroups).map(durations => {
      if (durations.length === 0) return 0;
      return durations.reduce((sum, duration) => sum + duration, 0) / durations.length;
    });

    console.log('不同时段平均巡逻时长数据:', shiftData);
    return shiftData;
  } catch (error) {
    console.error('获取平均巡逻时长失败:', error);
    return [];
  }
};

// 获取不同区域的平均巡逻时长
const getAveragePatrolTimeByArea = async () => {
  try {
    // 修正API路径
    const response = await api.get(`${API_BASE_URL}/shifts`);
    const shifts = response.data || [];
    console.log('不同区域巡逻时长，获取到的排班数据:', shifts);

    // 动态创建区域分组
    const areaGroups = {};

    // 先遍历所有班次，获取所有不同的区域
    shifts.forEach(shift => {
      const area = shift.location || '默认区域';
      if (!areaGroups[area]) {
        areaGroups[area] = [];
      }
    });

    // 如果没有任何区域，使用默认区域
    if (Object.keys(areaGroups).length === 0) {
      areaGroups['默认区域'] = [];
    }

    // 再次遍历班次，计算每个区域的巡逻时长
    shifts.forEach(shift => {
      // 检查必要字段是否存在
      if (!shift.startTime || !shift.endTime || !shift.date) {
        console.warn('班次数据缺少时间信息:', shift);
        return;
      }

      // 正确解析日期时间
      const startDateTime = new Date(`${shift.date}T${shift.startTime}`);
      const endDateTime = new Date(`${shift.date}T${shift.endTime}`);

      // 检查日期是否有效
      if (isNaN(startDateTime.getTime()) || isNaN(endDateTime.getTime())) {
        console.warn('班次日期时间解析失败:', shift);
        return;
      }

      // 计算时长（小时）
      const duration = (endDateTime.getTime() - startDateTime.getTime()) / (1000 * 60 * 60);

      // 使用location作为区域，如果没有则使用默认区域
      const area = shift.location || '默认区域';

      // 将时长添加到对应区域的数组中
      areaGroups[area].push(duration);
    });

    // 获取所有区域名称
    const areaNames = Object.keys(areaGroups);
    console.log('实际区域名称:', areaNames);

    // 按日期分组计算每天的平均值
    const weekdays = ['周一', '周二', '周三', '周四', '周五'];
    const areaData = [];

    // 为每个区域生成一周的数据
    for (const area of areaNames) {
      const dailyData = [];
      const durations = areaGroups[area];

      // 为每天分配数据
      for (let i = 0; i < 5; i++) {
        // 实际项目中应该根据日期筛选数据
        // 这里简单模拟，按顺序分配数据
        const dayData = durations.slice(i * 2, (i + 1) * 2);
        const avgDuration = dayData.length > 0
          ? dayData.reduce((sum, duration) => sum + duration, 0) / dayData.length
          : 0;
        dailyData.push(avgDuration);
      }
      areaData.push(dailyData);
    }

    console.log('不同区域平均巡逻时长数据:', areaData);
    return { areaData, areaNames };
  } catch (error) {
    console.error('获取区域平均巡逻时长失败:', error);
    return {
      areaData: [[], [], [], []],
      areaNames: ['区域A', '区域B', '区域C', '区域D']
    };
  }
};

// 获取不同区域的出勤次数
const getAttendanceCountByArea = async () => {
  try {
    // 修正API路径
    const response = await api.get('/patrol/points');
    const patrolPoints = response.data.data;
    console.log('response获取到的巡逻点数据:', patrolPoints);

    // 按区域分组统计已签到的巡逻点数量
    const areaMap = new Map();
    patrolPoints.forEach(point => {
      console.log("point.patrolName: " + point.patrolName)
      if (point.status === 1 && point.patrolName) { // 只统计已签到的点
        if (areaMap.has(point.patrolName)) {
          areaMap.set(point.patrolName, areaMap.get(point.patrolName) + 1);
        } else {
          areaMap.set(point.patrolName, 1);
        }
      }
    });

    // 转换为数组
    const areaData = Array.from(areaMap.values());
    const areaNames = Array.from(areaMap.keys());
    console.log('区域名称:', areaNames);
    console.log('区域出勤次数数据:', areaData);

    // 如果没有数据，提供默认值
    if (areaData.length === 0) {
      return {
        areaData: [20, 15, 25, 18, 22],
        areaNames: ['区域A', '区域B', '区域C', '区域D', '区域E']
      };
    }

    return { areaData, areaNames };
  } catch (error) {
    console.error('获取区域出勤次数失败:', error);
    // 出错时提供默认值
    return {
      areaData: [20, 15, 25, 18, 22],
      areaNames: ['区域A', '区域B', '区域C', '区域D', '区域E']
    };
  }
};

// 获取不同部门的出勤次数
const getAttendanceCountByDepartment = async () => {
  try {
    // 获取班次数据
    const shiftsResponse = await api.get(`${API_BASE_URL}/shifts`);
    const shifts = shiftsResponse.data || [];
    console.log('获取到的班次数据:', shifts);

    // 获取警员数据
    const officersResponse = await api.get(`${API_BASE_URL}/officers`);
    const officers = officersResponse.data?.data || [];
    console.log('获取到的警员数据:', officers);

    // 创建警员姓名到部门的映射
    const officerNameToDepartmentMap = new Map();
    officers.forEach(officer => {
      if (officer.name && officer.department) {
        officerNameToDepartmentMap.set(officer.name, officer.department);
      }
    });

    console.log("警员姓名到部门的映射:");
    officerNameToDepartmentMap.forEach((department, officerName) => {
      console.log(`警员姓名: ${officerName}, 部门: ${department}`);
    });

    // 按部门分组统计出勤次数
    const departmentMap = new Map();

    shifts.forEach(shift => {
      if (shift.officerNames && shift.officerNames.length > 0) {
        // 遍历班次中的所有警员
        shift.officerNames.forEach(officerName => {
          const department = officerNameToDepartmentMap.get(officerName);
          if (department) {
            if (departmentMap.has(department)) {
              departmentMap.set(department, departmentMap.get(department) + 1);
            } else {
              departmentMap.set(department, 1);
            }
          }
        });
      }
    });

    // 打印部门映射统计结果
    console.log("部门出勤次数统计:");
    departmentMap.forEach((count, department) => {
      console.log(`部门: ${department}, 出勤次数: ${count}`);
    });

    // 转换为饼图数据格式
    const departmentData = Array.from(departmentMap.entries()).map(([name, value]) => ({
      value,
      name
    }));

    console.log('部门出勤次数数据:', departmentData);

    // 如果没有数据，提供默认值
    if (departmentData.length === 0) {
      return [
        { value: 100, name: '部门A' },
        { value: 150, name: '部门B' },
        { value: 200, name: '部门C' },
        { value: 120, name: '部门D' }
      ];
    }

    return departmentData;
  } catch (error) {
    console.error('获取部门出勤次数失败:', error);
    // 出错时提供默认值
    return [
      { value: 100, name: '部门A' },
      { value: 150, name: '部门B' },
      { value: 200, name: '部门C' },
      { value: 120, name: '部门D' }
    ];
  }
};

onMounted(async () => {
  if (chart.value) {
    const myChart = echarts.init(chart.value);

    let option: any = {};

    if (props.title === '在职警员数量') {
      const monthlyData = await getOfficerCountByMonth();
      option = {
        title: {
          text: '月度变化趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月']
        },
        yAxis: {
          type: 'value'
        },
        series: [ {
          data: monthlyData,
          type: 'line',
          smooth: true,
          lineStyle: {
            width: 3,
            color: '#6f42c1'
          },
          itemStyle: {
            color: '#6f42c1'
          }
        } ]
      };
    } else if (props.title === '平均巡逻时长') {
      const shiftData = await getAveragePatrolTimeByShift();
      option = {
        title: {
          text: '不同时段对比',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: ['早班', '中班', '晚班', '夜班']
        },
        yAxis: {
          type: 'value',
          name: '小时'
        },
        series: [ {
          data: shiftData,
          type: 'bar',
          barWidth: '40%',
          itemStyle: {
            color: '#0dcaf0'
          }
        } ]
      };
    } else if (props.title === '本月出勤次数') {
      const { areaData, areaNames } = await getAttendanceCountByArea();
      option = {
        title: {
          text: '区域出勤对比',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['出勤次数']
        },
        xAxis: {
          type: 'category',
          data: areaNames
        },
        yAxis: {
          type: 'value'
        },
        series: [ {
          name: '出勤次数',
          data: areaData,
          type: 'bar',
          showBackground: true,
          backgroundStyle: {
            color: 'rgba(180, 180, 180, 0.2)'
          },
          itemStyle: {
            color: '#ffc107'
          }
        } ]
      };
    }

    myChart.setOption(option);
    window.addEventListener('resize', () => myChart.resize());
  }

  if (middleChart.value) {
    const middleMyChart = echarts.init(middleChart.value);

    let middleOption: any = {};

    if (props.title === '在职警员数量') {
      const { departmentData, departmentNames } = await getOfficerCountByDepartment();
      middleOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: departmentNames
        },
        yAxis: {
          type: 'value',
          show: false // 隐藏Y轴
        },
        series: [ {
          data: departmentData,
          type: 'bar',
          barWidth: '40%',
          itemStyle: {
            color: '#6f42c1'
          },
          label: {
            show: true,
            position: 'top',
            fontSize: 8
          }
        } ],
        grid: {
          left: '10%',
          right: '5%',
          bottom: '10%',
          top: '10%',
          containLabel: true
        }
      };
    } else if (props.title === '平均巡逻时长') {
      const { areaData, areaNames } = await getAveragePatrolTimeByArea();
      middleOption = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: areaNames,
          textStyle: {
            fontSize: 8
          },
          top: '0%'
        },
        xAxis: {
          type: 'category',
          data: ['周一', '周二', '周三', '周四', '周五'],
          axisLabel: {
            fontSize: 8
          }
        },
        yAxis: {
          type: 'value',
          name: '小时',
          nameTextStyle: {
            fontSize: 8
          },
          axisLabel: {
            fontSize: 8
          }
        },
        series: areaNames.map((area, index) => ({
          name: area,
          type: 'line',
          data: areaData[index] || [],
          lineStyle: {
            width: 2
          }
        }) ),
        grid: {
          left: '10%',
          right: '10%',
          bottom: '15%',
          top: '20%',
          containLabel: true
        }
      };
    } else if (props.title === '本月出勤次数') {
      const departmentData = await getAttendanceCountByDepartment();
      middleOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: '5%',
          top: 'center',
          textStyle: {
            fontSize: 8
          }
        },
        series: [
          {
            name: '出勤次数',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '12',
                fontWeight: 'bold'
              }
            },
            data: departmentData
          }
        ]
      };
    }

    middleMyChart.setOption(middleOption);
    window.addEventListener('resize', () => middleMyChart.resize());
  }

  // 将数据传递给父组件
  const updatedStat = {
    icon: props.icon,
    iconBgColor: props.iconBgColor,
    title: props.title,
    value: props.value,
    comparison: props.comparison,
    chartData: props.chartData // 如果需要传递图表数据，可以在这里添加
  };
  console.log(updatedStat)
  emit('updateStatsData', updatedStat); // 触发事件，将数据传递给父组件
});
</script>

<style scoped>
@import "@/assets/styles/views/admin/StatCard.css";
.stat-card {
  display: flex;
  padding: 1rem;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  height: 250px; /* 增加卡片高度 */
}

.card-content {
  flex: 1;
  max-width: 35%; /* 调整内容区域的宽度 */
}

.card-title {
  display: flex;
  align-items: center;
  margin-bottom: 0.5rem;
}

.icon-wrapper {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 0.75rem;
  color: white;
}

.icon {
  width: 20px;
  height: 20px;
}

.card-value {
  font-size: 1.5rem;
  font-weight: bold;
  margin-bottom: 0.5rem;
}

.card-comparison {
  font-size: 0.875rem;
}

.chart-middle-container {
  flex: 1;
  min-width: 150px;
  height: 100%; /* 增加中间图表的高度，使其占满剩余空间 */
  margin: 0 1rem;
}

.middle-chart {
  width: 100%;
  height: 100%;
}

.chart-container {
  flex: 1;
  min-width: 150px;
  height: 100%; /* 增加右侧图表的高度，使其占满剩余空间 */
  margin-left: 1rem;
}

.chart {
  width: 100%;
  height: 100%;
}
</style>
